<script setup lang="ts">
defineOptions({name:'TradeMark'})
import {ref, onMounted, reactive} from 'vue'
import {reqHasTrademark, reqAddOrUpdateTrademark, reqDeleteTrademark} from '@/api/product/trademark/index.ts'
import {TradeMarkResponseData,Records,TradeMark} from '@/api/product/trademark/type.ts'
import {ElMessage, UploadProps} from "element-plus";
const pageNo = ref<number>(1) //第几页
const pageSize = ref<number>(3) //每页数量
const total = ref<number>() //总数
const tradeMark = ref<Records>([])

/**
 * 获取商品数据
 */
const getHasTrademark =async ()=>{
  const res:TradeMarkResponseData = await reqHasTrademark(pageNo.value,pageSize.value)
  if(res.code==200){
    total.value=res.data.total
    tradeMark.value=res.data.records
    // console.log(res)
  }
}
onMounted(()=>{
   getHasTrademark()
})
/**
 * 改变页码触发
 */
const changePageSize= ()=>{
  pageNo.value=1
  getHasTrademark()
}
/**
 * 改变每页数量时触发
 */
const changePageNo= ()=>{
   getHasTrademark()
}
//控制弹框显示
const dialogFormVisible = ref(false)
/**
 * 新增品牌数据
 */
const trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: ''
})
/**
 *添加品牌
 */
const addTradeMark =()=>{
  dialogFormVisible.value=true//显示对话框
  //清空收集数据
  trademarkParams.tmName=''
  trademarkParams.logoUrl=''
  trademarkParams.id=0
  //添加之前情况校验结果
  formRef.value?.clearValidate('tmName')
  formRef.value?.clearValidate('logoUrl')
}
/**
 *更新品牌
 */
const updateTradeMark =(row:TradeMark)=>{
  //对话框显示
  dialogFormVisible.value=true
  //展示已有品牌的数据
  Object.assign(trademarkParams,row)
  // trademarkParams.tmName=row.tmName
  // trademarkParams.logoUrl=row.logoUrl
  // trademarkParams.id=row.id
  //添加之前情况校验结果
  formRef.value?.clearValidate('tmName')
  formRef.value?.clearValidate('logoUrl')
}
/**
 * 取消添加
 */
const cancel = () => {
  dialogFormVisible.value=false
}
// 表单实例
const formRef= ref()
/**
 * 确定添加品牌
 */
const confirm = async () => {
  //校验表单
  await formRef.value?.validate()
  const res = await reqAddOrUpdateTrademark(trademarkParams)
  // console.log(res)
  if(res.code==200){
    dialogFormVisible.value=false
    ElMessage({
      type:'success',
      message:trademarkParams.id?'修改品牌成功':'添加品怕失败'
    })
    trademarkParams.id?pageNo.value=1:pageNo.value
    await getHasTrademark()
  }else {
    ElMessage({
      type:'error',
      message:trademarkParams.id?'修改品牌失败':'添加品怕失败'
    })
  }
}
/**
 * 上传文件的约束
 * @param rawFile
 */
const beforeUpload:UploadProps['beforeUpload'] = (rawFile) => {
  if(rawFile.type=='image/png'||rawFile.type=='image/jpeg'||rawFile.type=='image/gif'){
    if(rawFile.size/1024/1024<4){
      return  true
    }else{
      ElMessage({
        type:'error',
        message:'上传文件大小小于4M'
      })
      return  false
    }
  }else{
    ElMessage({
      type:'error',
      message:'上传文件格式必须是PNG|JPG|GIF'
    })
    return false;
  }
}
/**
 *文件上传成功后的回调
 * @param response 服务器返回的数据
 */
const uploadSuccess:UploadProps['onSuccess'] = (response) => {
  // console.log(response)
  // 手机图片的地址
  trademarkParams.logoUrl=response.data
  // 图片上传成功清除图片校验结果
  formRef.value?.clearValidate('logoUrl')
}
/**
 * 名称校验
 * @param _
 * @param value
 * @param callBack
 */
const validatorTmName=(_:any,value:any,callBack:any)=>{
  if(value?.trim().length>=2){
    callBack()
  }else{
    callBack(new Error('品牌的名称长度必须大于等于两位'))
  }
}
/**
 * 图片URL校验
 * @param rule
 * @param value
 * @param callBack
 */
const validatorLogoUrl = (_:any,value:any,callBack:any) => {
  if(value){
    callBack()
  }else {
    callBack(new Error('图片没有上传！'))
  }
}
//校验规则
const rules={
  tmName: [{required:true,trigger:'blur',validator:validatorTmName}],
  logoUrl: [{required:true,trigger:'blur',validator:validatorLogoUrl}]
}
/**
 * 删除商品的功能
 * @param id 商品ID
 */
const removeTrademark = async(id:string) => {
  const res = await reqDeleteTrademark(id)
  if(res.code==200){
    ElMessage({
      type:'success',
      message:'删除成功'
    })
    pageNo.value=tradeMark.value.length>1?pageNo.value:pageNo.value-1
    await getHasTrademark()
  }else {
    ElMessage({
      type:'success',
      message:'删除失败'
    })
  }
}
</script>

<template>
  <el-card class="box-card">
<!--    v-if="userStore.buttons.includes('btn.Trademark.add')"-->
    <el-button type="primary" size="default" icon="Plus" @click="addTradeMark" v-has="`btn.Trademark.add`">添加品牌</el-button>
    <el-table :data="tradeMark" style="width: 100%;margin-top: 15px" border>
      <el-table-column label="序号" width="80" align="center" type="index"/>
      <el-table-column prop="tmName" label="品牌名称"/>
      <el-table-column prop="logoUrl" label="品牌LOGO">
        <template #default="{row}">
          <el-image
              style="width: 100px; height: 100px"
              :src="row.logoUrl"
              alt="图片加载失败"
          />
        </template>
      </el-table-column>
      <el-table-column prop="address1" label="品牌的操作" >
        <template #default="{row}">
          <el-button type="warning" icon="Edit" @click="updateTradeMark(row)"></el-button>
          <el-popconfirm
              title="您确定要删除该品牌吗？"
              icon="Delete"
              width="250px"
              @confirm="removeTrademark(row.id)"
              confirm-button-text="确认"
              cancel-button-text="取消"
          >
            <template #reference>
              <el-button type="danger" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[3,5,7,9]"
        :disabled="false"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @size-change="changePageSize"
        @current-change="changePageNo"
        style="margin-top: 15px"
    />
  </el-card>
<!--  添加商品的对话框-->
  <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id?'修改品牌':'添加品牌'">
    <el-form style="width: 80%" :model="trademarkParams" :rules="rules" ref="formRef">
      <el-form-item label="品牌名称:" label-width="100" prop="tmName">
        <el-input  autocomplete="off" placeholder="请输入品牌名称" v-model="trademarkParams.tmName"/>
      </el-form-item>
      <el-form-item label="品牌LOGO:" label-width="100" prop="logoUrl">
        <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
            @on-success="uploadSuccess"
        >
          <img v-if="trademarkParams.logoUrl"
               :src="trademarkParams.logoUrl"
               style="width: 100px; height: 100px"
               class="avatar"
               alt="图片"/>
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>